package com.dawnling.androidutils.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dawnling.androidutils.R;
import com.dawnling.androidutils.adapter.MyPhotoAdater;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PhotoActivity extends AppCompatActivity {

    private ImageView imgTest;
    private RecyclerView recyclerView;
    private MyPhotoAdater photoAdapter;
    private List<String> photoList = new ArrayList<>();
    public static final int REQUEST_CODE_CAMERA = 110;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);

        initPermission();
        imgTest = findViewById(R.id.imgTest);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        photoAdapter = new MyPhotoAdater(this);
        recyclerView.setAdapter(photoAdapter);

        photoList.clear();
        //默认三个空白图片
        for (int i = 0; i < photoLimitShow; i++){
            photoList.add("");
        }
        photoAdapter.setNewData(photoList);

        //点击跳转拍照
        photoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if ("".equals(photoAdapter.getItem(position))) {
                    useCamera();
                }else {
                    //浏览大图
                    Toast.makeText(PhotoActivity.this, "浏览大图", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //删除按钮
        photoAdapter.mListener = new MyPhotoAdater.Listener() {
            @Override
            public void deleteClick(int position) {
                photoAdapter.remove(position);
                usingPhotoSize --;
                //新增空白图 固定3张
                if (photoList.size() <= photoLimitShow){
                    for (int j = 0; j < photoLimitShow - photoList.size(); j++){
                        photoList.add("");
                    }
                }
                //处理删除操作，小于最大限制一直加一个空白
                if ((usingPhotoSize+1) == photoLimit)
                    photoList.add(usingPhotoSize, "");
                photoAdapter.notifyDataSetChanged();
            }
        };

        imgTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useCamera();
            }
        });
    }

    /**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/keytop/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();
        //改变Uri 文件路径注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.dawnling.androidutils.fileProvider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    public void initPermission(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA}, 0);
        }
    }

    //获取有效图片数量
    private int usingPhotoSize = 0;
    private int photoLimitShow = 3;//列表至少3个空白按钮
    private int photoLimit = 5;//限制几张
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            //适配7.0以上手机
            Log.e("TAG", "---------" + FileProvider.getUriForFile(this, "com.dawnling.androidutils.fileProvider", file));
            imgTest.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            String imgPath = file.getAbsolutePath();
            Log.e("图片地址：", imgPath);

            if (!imgPath.isEmpty()) usingPhotoSize++;
            for (int i = 0; i < photoList.size(); i++) {
                if ("".equals(photoList.get(i))) {
                    photoAdapter.remove(i);
                    photoList.add(i, imgPath);
                    if (usingPhotoSize >= photoLimitShow && photoList.size() < photoLimit) {
                        photoList.add(usingPhotoSize, "");
                    }
                    return;
                }
            }
        }
    }

//    public void getLnt(){
//        ExifInterface exifInterface = new ExifInterface(imagePath);
//        String latValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
//        String lngValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
//        String latRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
//        String lngRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
//    }
}
